import 'package:flutter/material.dart';
import 'package:x3_base_package/x3_base_package.dart';
import 'package:x3_business_core/business_customer/ful_components/business_customer_details_tag_button.dart';

class BusinessCustomerDetailsTagEditTest extends StatefulWidget {

  static String sName = 'BusinessCustomerDetailsTagEditTest';

  @override
  _BusinessCustomerDetailsTagEditTestState createState() => _BusinessCustomerDetailsTagEditTestState();

}

class _BusinessCustomerDetailsTagEditTestState extends State<BusinessCustomerDetailsTagEditTest> {

  String _vipId;

  List _addedTags;

  List _notAddedTags;

  Map<String, int> _store = {};

  //是否允许执行（节流）
  bool canExecute = true;

  void _updateTabs({String deleteTagId = '', String addTagId = ''}) {
    setState(() {
      if (deleteTagId.isNotEmpty) {
        _addedTags.removeWhere((element) => element['key'] == deleteTagId);
        List _currentTags = _notAddedTags[_store[deleteTagId]]['tags'] as List;
        Map tag = _currentTags.firstWhere((element) => element['key'] == deleteTagId);
        tag['issel'] = false;
      }
      if (addTagId.isNotEmpty) {
        List _currentTags = _notAddedTags[_store[addTagId]]['tags'] as List;
        Map tag = _currentTags.firstWhere((element) => element['key'] == addTagId);
        tag['issel'] = true;
        _addedTags.add({'key': addTagId, 'value': tag['value']});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    dynamic arguments = BaseRouterUtil.getArguments(context);
    _vipId = BaseUtils.getKeyData(arguments, 'vipId').toString();
    return BaseScaffoldComponent(
      willPopScope: _onPop,
      title: '添加标签',
      child: BaseScreenRefreshComponent(
        request: BaseScreenRequestModel('/vip/customer/tag/query/viptagedit/{vipId}', params: {'vipId': _vipId}, method: BaseHttpMethodEnum.GET),
        builder: (result) {
          if (result.success != true) return BaseEmptyComponent();
          var data = result.data;
          _addedTags = data['addedTags'] ?? [];
          _notAddedTags = data['notaddedTags'] ?? [];
          return _buildContent();
        },
      ),
    );
  }

  Widget _buildContent() {
    return ListView(
      children: [
        _buildAddedTabs(),
        _buildNotAddedTabs(),
      ],
    );
  }

  Widget _buildAddedTabs() {
    return Container(
      margin: EdgeInsets.only(bottom: 12),
      child: _buildTabsCard(
        title: '已添加标签',
        subtitle: '',
        body: Container(padding: EdgeInsets.symmetric(vertical: 6), child: BaseWrapExpandDown(data: _addedTags, builder: _buildAddChipButton, limit: _addedTags.length)),
      ),
    );
  }

  Widget _buildNotAddedTabs() {
    List<Widget> children = [];
    for (int i = 0; i < _notAddedTags.length; i++) {
      /// 为了提高性能存储索引
      List _tags = _notAddedTags[i]['tags'] as List;
      for (int index = 0; index < _tags.length; index++) {
        Map data = _notAddedTags[i]['tags'][index];
        _store[data['key']] = i;
      }
      if (_tags.length > 0) children.add(_buildNotAddList(i, _notAddedTags[i]));
    }
    return _buildTabsCard(
      title: '所有标签',
      body: ListView(physics: NeverScrollableScrollPhysics(), shrinkWrap: true, children: children),
    );
  }

  /// 通用布局
  Widget _buildTabsCard({@required String title, String subtitle, @required Widget body}) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.only(top: 4),
            child: RichText(
              text: TextSpan(
                children: [
                  TextSpan(text: title, style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14)),
                  WidgetSpan(child: SizedBox(width: 6)),
                  TextSpan(text: subtitle ?? '', style: Theme.of(context).textTheme.subtitle2),
                ],
              ),
            ),
          ),
          Divider(height: 8, endIndent: 0, indent: 0),
          body
        ],
      ),
    );
  }

  /// 已添加标签 状态 按钮
  Widget _buildAddChipButton(dynamic item) {
    String label = item['value'] ?? '';
    String value = item['key'] ?? '';
    return BusinessCustomerDetailsTagButton(
      label: label,
      value: value,
      onDeleted: () {
        _onDeleteVipTagAlert(value);
      },
      onDoubleTap: () {
        _onDeleteVipTagAlert(value);
      },
    );
  }

  /// 所有标签列表
  Widget _buildNotAddList(int index, dynamic item) {
    String tagTypeName = item['tagTypeName'] ?? '';
    int tagSelType = item['tagSelType'] ?? 0;
    String tagSelTypeName = item['tagSelTypeName'] ?? '';
    List tags = item['tags'] ?? [];
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.only(top: 12, bottom: 8),
            child: Text('$tagTypeName($tagSelTypeName):', style: Theme.of(context).textTheme.bodyText2),
          ),
          BaseWrapExpandDown(
            data: tags,
            limit: tags.length,
            builder: (item) {
              return _buildNotAddButton(item, tagSelType);
            },
          ),
        ],
      ),
    );
  }

  /// 所有按钮
  Widget _buildNotAddButton(dynamic item, int tagSelType) {
    String label = item['value'] ?? '';
    String value = item['key'] ?? '';
    bool isSel = item['issel'] ?? false;
    return BusinessCustomerDetailsTagButton(
      label: label,
      isSelected: !isSel,
      value: value,
      onTap: () async {
        _onSaveVipTag(item, tagSelType);
      },
    );
  }

  /// 删除标签弹窗
  void _onDeleteVipTagAlert(String tagId) {
    if (!canExecute) return;
    canExecute = false;
    Future.delayed(Duration(microseconds: 500)).then((e) {
      canExecute = true;
    });
    BaseComponentUtils.showCommonDialog(context, content: '是否删除该标签？', onOKPress: () {
      _onDeleteVipTag(tagId).then((e) {
        if (e == true) {
          _updateTabs(deleteTagId: tagId);
          Navigator.pop(context);
        }
      });
    });
  }

  /// 保存标签
  void _onSaveVipTag(dynamic item, int tagSelType) async {
    if (item['issel'] == true) return;
    if (!canExecute) return;
    canExecute = false;
    Future.delayed(Duration(microseconds: 500)).then((e) {
      canExecute = true;
    });

    String tagId = item['key'];
    String deleteTagId = '';
    // 如果是单选  0 单选 、 1 多选
    if (tagSelType == 0) {
      // 把原来的删除
      List _currentTags = _notAddedTags[_store[tagId]]['tags'] as List; // 找出当前tags组
      List _currentTagsKeys = _currentTags.map((e) => e['key']).toList();
      bool isExist = _addedTags.any((element) => _currentTagsKeys.contains(element['key']));
      if (isExist == true) {
        var isExistTag = _addedTags.firstWhere((element) => _currentTagsKeys.contains(element['key']));
        deleteTagId = isExistTag['key'];
        bool res = await _onDeleteVipTag(deleteTagId);
        if (res == false) return;
      }
    }
    BaseHttpResultModel saveResult = await dioUtil.fetch('/vip/customer/tag/save/viptag', params: {'tagId': tagId, 'vipId': _vipId});
    if (saveResult.success == true) {
      _updateTabs(deleteTagId: deleteTagId, addTagId: tagId);
    }
  }

  /// 删除标签
  Future<bool> _onDeleteVipTag(String tagId) async {
    BaseHttpResultModel result = await dioUtil.fetch('/vip/customer/tag/del/viptag', params: {'tagId': tagId, 'vipId': _vipId});
    return result.success;
  }

  /// 返回
  Future<bool> _onPop() async {
    BaseRouterUtil().pop(_addedTags);
    return Future.value(false);
  }
}
